﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Exhort.Backstage.Components;
using Exhort.Entity.Basic;
using Exhort.Resolver;
using Exhort.Utility.Entities;
using Microsoft.AspNetCore.Mvc;

namespace Exhort.Backstage.Areas.Basic.Controllers
{
    [Area("Basic")]
    public class UserController : WorkController
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult UpdatePwd()
        {
            return View();
        }

        public IActionResult Update()
        {
            return View();
        }

        public string Get(string id)
        {
            var entity = ServiceResolver.BasicUser.Get(id);

            var ignore = new string[] { "PassWord" };

            return ServiceResult.Operation(entity != null, data: entity).Serialize(ignore: ignore);
        }

        public string GetCurrent()
        {
            var entity = ServiceResolver.BasicUser.Get(UserID);

            var ignore = new string[] { "PassWord" };

            return ServiceResult.Operation(entity != null, data: entity).Serialize(ignore: ignore);
        }

        public string Grid(int rows, int page, string search)
        {
            var list = ServiceResolver.BasicUser.Grid(rows, page, search, out int total);

            var ignore = new string[] { "PassWord" };

            return ServiceResult.Success(data: new { rows = list, total }).Serialize(ignore: ignore);
        }

        public string Save(BasicUser model)
        {
            return ServiceResolver.BasicUser.Save(model).Serialize();
        }

        public string Remove(string id)
        {
            return ServiceResolver.BasicUser.Delete(id).Serialize();
        }

        public string ResetPwd(string id, string pwd)
        {
            return ServiceResolver.BasicUser.ResetPwd(id, pwd, UserName).Serialize();
        }

        [HttpPost]
        public string UpdatePwd(string id, string oldpwd, string newpwd)
        {
            return ServiceResolver.BasicUser.UpdatePwd(id, oldpwd, newpwd).Serialize();
        }

        public string Enable(string id, bool bit)
        {
            return ServiceResolver.BasicUser.Enable(id, bit).Serialize();
        }

        public string GetPower(string id)
        {
            var list = ServiceResolver.BasicUserRole.Grid(id);

            return ServiceResult.Success(data: list.Select(m => m.RoleID)).Serialize();
        }

        public string SetPower(string id, string[] values)
        {
            return ServiceResolver.BasicUserRole.SetRoles(id, values).Serialize();
        }
    }
}